#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main(int argc, char *argv[])
{
    FILE *fpi = NULL;
    FILE *fpo = NULL;
    unsigned char *pbuffer = NULL;
    unsigned int length = 0;
    int i;

    if(argc != 4)
    {
        printf("将文件转换成C语言的数组工具\n");
        printf("用法：\n");
        printf("%s -o 输出文件 输入文件\n", argv[0]);
        return 0;
    }
    i = 1;
    while(i<argc)
    {
        if(strcmp(argv[i],"-o")==0)
        {
            i++;
            if(i<argc)
            {
                fpo = fopen(argv[i],"wb");
                if(!fpo)
                {
                    printf("目标文件无法创建！\n");
                    return -1;
                }
            }
        }
        else
        {
            fpi = fopen(argv[i],"rb");
            if(!fpi)
            {
                printf("源文件打开出错！\n");
                return -1;
            }
            fseek(fpi,0,SEEK_END);
            length = ftell(fpi);
            fseek(fpi,0,SEEK_SET);
            if(length > 0)
            {
                pbuffer = (unsigned char *)malloc(length);
                if(!pbuffer)
                {
                    printf("内存不足！\n");
                    return -1;
                }
                fread(pbuffer,sizeof(unsigned char),length,fpi);
                fclose(fpi);
            }
        }
        i++;
    }

    if(pbuffer && fpo)
    {
        fprintf(fpo, "const unsigned char cdata[%u] = {\n\t", length);
        for(i=0;i<length;i++)
        {
            fprintf(fpo,"0x%02x,", pbuffer[i]);
            if((i+1)%16==0)
            {
                fprintf(fpo,"\n\t");
            }
        }
        fprintf(fpo, "\n};\n");
        free(pbuffer);
        fclose(fpo);
    }
    return 0;
}
